package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.PersonGiftListAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.MineExcitationObject;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnPersonGiftCostListener;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.smarttop.library.utils.LogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * Created by DELL on 2017/10/27.
 * ta的小礼
 */

public class PersonGiftActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = PersonGiftActivity.class.getSimpleName();

    public static void jump(Activity activity, String userId) {
        Intent intent = new Intent(activity, PersonGiftActivity.class);
        intent.putExtra("userId", userId);
        activity.startActivityForResult(intent, 1001);
    }

    public static void jump(Fragment fragment, String userId) {
        Intent intent = new Intent(fragment.getActivity(), PersonGiftActivity.class);
        intent.putExtra("userId", userId);
        fragment.startActivityForResult(intent, 1001);
    }

    private Button mBack;
    private TextView mTitle, mConvertIntegration, mCommit, mEmptyText, mRefresh, mTextCommit;
    private RecyclerView mRecyclerView;
    private View mLine;
    private LinearLayout mLinear;
    private RelativeLayout mEmpty, mError;
    private SmartRefreshLayout mSmartRefreshLayout;

    private String mUserId;
    private PersonGiftListAdapter mAdapter;
    private ArrayList<MineExcitationObject> mList;
    private String giftIds;//多个id用英文,分割
    private Map<String, MineExcitationObject> exchangeGifts;
    private int page = 1;
    private int totlaPage;
    private boolean dataIsChange = false;
    private int num = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_gift);
        mUserId = getIntent().getStringExtra("userId");
        initView();
        initListener();
        updateText(0);
        initAdapter();
        setSmartRefreshLayout();
    }

    private void initView() {
        mBack = findViewById(R.id.title_left_button);
        mTitle = findViewById(R.id.title_text_title);
        mConvertIntegration = findViewById(R.id.convert_integration);
        mCommit = findViewById(R.id.commit);
        mRecyclerView = findViewById(R.id.list);
        mLine = findViewById(R.id.line);
        mLinear = findViewById(R.id.ll);
        mEmpty = findViewById(R.id.empty);
        mError = findViewById(R.id.error);
        mEmptyText = findViewById(R.id.empty_text);
        mRefresh = findViewById(R.id.fresh);
        mTextCommit = findViewById(R.id.title_rigth_text);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);

        mRecyclerView.setLayoutManager(new GridLayoutManager(PersonGiftActivity.this, 3));
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(PersonGiftActivity.this, 10), Utils.dip2px(PersonGiftActivity.this, 10), Utils.dip2px(PersonGiftActivity.this, 10)));

        if (TextUtils.isEmpty(mUserId) || mUserId.equals(Globals.getExcatationUserId())) {
            mLine.setVisibility(View.GONE);
            mLinear.setVisibility(View.GONE);
            mTextCommit.setVisibility(View.VISIBLE);
            mTitle.setText(R.string.my_gift);
        } else {
            mLine.setVisibility(View.GONE);
            mLinear.setVisibility(View.GONE);
            mTextCommit.setVisibility(View.GONE);
            mTitle.setText(R.string.ta_gift);
        }

        mEmptyText.setText("还没有获得小礼哦~");
    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mCommit.setOnClickListener(this);
        mTextCommit.setOnClickListener(this);
    }

    private void initAdapter() {
        if (mList == null) {
            mList = new ArrayList<>();
        }
        mAdapter = new PersonGiftListAdapter(PersonGiftActivity.this, mList, BitmapUtils.getDisplayWidth(this));
        mAdapter.registerOnPersonGiftCostListener(new OnPersonGiftCostListener() {
            @Override
            public void calculateGiftCost(double giftCost, String giftIds, Map<String, MineExcitationObject> exchangeGifts) {
                updateText(giftCost);
                PersonGiftActivity.this.giftIds = giftIds;
                PersonGiftActivity.this.exchangeGifts = exchangeGifts;
            }

        });
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getGift();
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if(!mSmartRefreshLayout.isEnableLoadmore()) mSmartRefreshLayout.setEnableLoadmore(true);
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (page <= totlaPage) {
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                    getGift();
                } else {
                    mSmartRefreshLayout.finishLoadmore();
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
    }

    /**
     * 获取个人小礼列表
     */
    public void getGift() {
        if (mEmpty.getVisibility() == View.VISIBLE) {
            mEmpty.setVisibility(View.GONE);
        }
        if (mError.getVisibility() == View.VISIBLE) {
            mError.setVisibility(View.GONE);
        }

        try {
            MinePresenter.getInstance().getUserGifts(Globals.getToken(), mUserId, page, 10, num, new DataResponseListener<BaseDataPageBody<MineExcitationObject>>() {
                @Override
                public void onSuccess(BaseDataPageBody<MineExcitationObject> dataResponse) {
                    if (page == 1) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                        mList.clear();
                    } else {
                        mSmartRefreshLayout.finishLoadmore(500, true);
                    }

                    mList.addAll(dataResponse.getInfo());
                    totlaPage = dataResponse.getTotalPage();
                    page++;
                    mAdapter.notifyDataSetChanged();

                    if (mList.size() == 0) {
                        mEmpty.setVisibility(View.VISIBLE);
                        mSmartRefreshLayout.setEnableLoadmore(false);
                    }
                }

                @Override
                public void onFail(String failMessage) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    if (mList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将会再次触发加载更多事件
                        mError.setVisibility(View.VISIBLE);
                    }
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    if (mList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将会再次触发加载更多事件
                        mError.setVisibility(View.VISIBLE);
                    }
                    toast(R.string.network_or_server_exception);
                }
            });
        } catch (Exception e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            if (mList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将会再次触发加载更多事件
                mError.setVisibility(View.VISIBLE);
            }
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }

    }

    /**
     * 通过不同颜色展示积分
     *
     * @param integrationCount
     */
    private void updateText(double integrationCount) {
        SpannableString ss = new SpannableString("兑换获得积分：" + integrationCount);
        ss.setSpan(new ForegroundColorSpan(Color.parseColor("#FF4138")), 7, ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        mConvertIntegration.setText(ss);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                onBack();
                break;
            case R.id.commit:
                //确认兑换
                if (!TextUtils.isEmpty(giftIds))
                    commitGift();
                break;
            case R.id.title_rigth_text:
                if (mAdapter != null) {
                    if (!mAdapter.getIsExchange()) {
                        if (mList != null && mList.size() > 0) {
                            mAdapter.setIsExchange(true);
                            mLine.setVisibility(View.VISIBLE);
                            mLinear.setVisibility(View.VISIBLE);
                            mTextCommit.setText(R.string.dismiss);
                        }
                    } else {
                        mAdapter.setIsExchange(false);
                        mLine.setVisibility(View.GONE);
                        mLinear.setVisibility(View.GONE);
                        mTextCommit.setText(R.string.exchange);
                    }
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    private void onBack() {
        Intent intent = new Intent();
        intent.putExtra("list", mList);
        intent.putExtra("dataIsChange", dataIsChange);
        setResult(0, intent);
        finish();
    }

    private void commitGift() {
        try {
            MinePresenter.getInstance().exchangeGift(Globals.getToken(), giftIds, new DataResponseListener() {
                @Override
                public void onSuccess(Object dataResponse) {
                    dataIsChange = true;
                    toast("积分已到账");
                    removeGiftWithExchangeGift();
                }

                @Override
                public void onFail(String failMessage) {
                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    toast(R.string.network_or_server_exception);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private void removeGiftWithExchangeGift() {
        Iterator<Map.Entry<String, MineExcitationObject>> ite = exchangeGifts.entrySet().iterator();
        while (ite.hasNext()) {
            mList.remove(ite.next().getValue());
        }
        mAdapter.exchangeSuccess();
        mAdapter.notifyDataSetChanged();
        if (mList.size() == 0) mEmpty.setVisibility(View.VISIBLE);
        updateText(0);
    }
}
